//
//  TF1to16ChatArea.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/5/16.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit


public class TF1to16ChatArea: UIView, UITableViewDelegate, UITableViewDataSource {

    //所有人禁言
    @objc var disableAll = false
    //单个禁言
    @objc var isDisable = false
    //用来 判断是不是自己
    @objc var uid:String = ""
    //无投票内容
    @objc let chcdtLabel = UILabel()
    //聊天
    @objc var tableView = UITableView()
    //聊天列表
    @objc var chatArray = NSMutableArray()
    //输入栏的容器
    let inputFieldView = UIView()
    let headerInSection = TFChatAnnouncementHeaderInSection()
    ////公告
    var forHeaderDict:TFAnnouncement?

    override init(frame: CGRect) {
        super.init(frame: frame)
  
        self.backgroundColor = UIColor(red: 28/255.0, green: 31/255.0, blue: 35/255.0, alpha: 0.98)
        self.tableView.backgroundColor =  UIColor.clear
        //不要下划线
        self.tableView.separatorStyle = .none
        
        self.tableView.delegate   = self
        self.tableView.dataSource = self
        self.addSubview(self.tableView)
        
        self.tableView.register(TF1to16ChatAreaCell.self, forCellReuseIdentifier: "TF1to16ChatAreaCell")
        self.tableView.register(TFChatPublicBroadcastingCell.self, forCellReuseIdentifier: "TFChatPublicBroadcastingCell")
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        }
        
        //投票内容
        self.chcdtLabel.numberOfLines = 0;
        self.addSubview(self.chcdtLabel)
        let votingContentLabelString = NSMutableAttributedString.getAttributed(string: "无聊天内容", font: UIFont.PingFang(size: 18), foregroundColor: UIColor(red: 173/255.0, green: 204/255.0, blue: 222/255.0, alpha: 1))
       
        self.chcdtLabel.textAlignment = .center
        self.chcdtLabel.attributedText = votingContentLabelString
         
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        self.chcdtLabel.frame = self.bounds
        
        let leftMargin:CGFloat = 5//左边距
        let rightMargin:CGFloat = 5//左边距
        
        let inputFieldViewW:CGFloat = self.frame.size.width-leftMargin-rightMargin
        var inputFieldViewH:CGFloat = 85.0
        let inputFieldViewX:CGFloat = leftMargin
        let inputFieldViewY:CGFloat = self.frame.size.height - inputFieldViewH - 5
        
        self.inputFieldView.frame = CGRect(x:inputFieldViewX, y:inputFieldViewY, width:inputFieldViewW, height:inputFieldViewH)

        if (self.disableAll||self.isDisable) {
            inputFieldViewH = 0
           }
        let tableViewH:CGFloat = self.frame.size.height
        
        self.tableView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: tableViewH-15)
        
        self.headerInSection.close.addTarget(self, action: #selector(closeClick), for: .touchUpInside)
       
    }
    @objc func closeClick()
    {
        self.forHeaderDict = nil
        self.tableView.reloadData()
    }
    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if (self.forHeaderDict != nil) {
       //头部视频
         return self.headerInSection
          }

         return nil
    }
    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if (self.forHeaderDict != nil) {
            
            let msg:String = self.forHeaderDict!.content
            
            let String = TalkfunSharedTools.getAttributedText(msg, fontSize: UIFont.PingFang(size: 14), foregroundColor: UIColor.white)
            
            //14  是左右边距
            
             let contentDict = TalkfunSharedTools.getSizeLabel(labelString: String, labelWidth:self.frame.size.width-18-18, labelfont: UIFont.PingFang(size: 14))
            
            
            
            //13  是上下的间距   20 是用户名字高度  3  是与名字的距离     10  是上间距
            let height = contentDict.height+36+10.5
      
            self.headerInSection.contentDictheight = contentDict.height
            self.headerInSection.viewWidth =  self.frame.size.width-7.5-7.5
            self.headerInSection.dict = self.forHeaderDict;
            return height;
            
        
        }
        return 0;
    }
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (self.chatArray.count>0) {
            self.chcdtLabel.isHidden = true
        }else{
            self.chcdtLabel.isHidden = false
        }
        
        return self.chatArray.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model =  self.chatArray[indexPath.row] as! TF1to16LiveChatData
         //奖杯  聊天
        if (model.isAward||model.isChat) {
            let  cell = tableView.dequeueReusableCell(withIdentifier: "TF1to16ChatAreaCell") as! TF1to16ChatAreaCell
            cell.selectionStyle = .none
            cell.backgroundColor = UIColor.clear
            cell.viewWidth = self.frame.size.width
         
            
            if (model.imageURL.count>0) {
                 

                 //  NSLog(@"图片-----------");
                var imageHight:CGFloat = 104
                if model.image != nil {
                    let image = model.image! as UIImage
                    if (image.size.width < self.frame.size.width-55-15) {
                        imageHight = image.size.height
                     }
                   
                }
                 //12名字是到图片的间距   24 是图片到与底边的间距
                let height:CGFloat = imageHight+36.5+12+24
                cell.viewHight = height
            }else{
                   cell.viewHight = 0;
            }
            
              
                cell.model =  model
                
                return cell;
        }else{
            //公共广播
            let  cell = tableView.dequeueReusableCell(withIdentifier: "TFChatPublicBroadcastingCell") as! TFChatPublicBroadcastingCell
            cell.selectionStyle = .none
            cell.backgroundColor = UIColor.clear
            cell.viewWidth = self.frame.size.width-26.5-26.5
            cell.model =  model
                   
                return cell;
            
        }
       
    }
    
    // 设置cell高度
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
           let  model =  self.chatArray[indexPath.row] as! TF1to16LiveChatData
           
           //奖杯
           if(model.isAward){
           
               return 60.5
           
           }else  if(model.isChat){
             
               //内容是图片
               if (model.imageURL.count>0) {

                   var imageHight:CGFloat = 104
                   if model.image == nil {
                       imageHight = 22;
                   }else if(model.image != nil){
                       
                       let width:CGFloat = model.image!.size.width
                       if width<self.frame.size.width-55-15 {
                           let imageHight2:CGFloat = model.image!.size.height
                           imageHight = imageHight2
                       }
                       
                   }
    
                   //12名字是到图片的间距   24 是图片到与底边的间距
                   let height = imageHight+36.5+12+24
                 return height
               }else {
                   //聊天

                  
       //        NSLog(@"women 不存在 bit");
                   
                let contentAttrStr = TalkfunSharedTools.getAttributedText(model.msg, fontSize: UIFont.PingFang(size: 14), foregroundColor: UIColor.white)
                   
                   
                   let reversedArray:NSArray = model.replyList.reverseObjectEnumerator().allObjects as NSArray

                   for i in 0..<reversedArray.count

                   {
                       let reply = reversedArray[i] as! TFChatReply
                       
                       var aa:String = ""
                       
                           aa = aa + "@"
                           aa = aa+(reply.nickname as String)
                       
                           aa = aa+(" " as String)

                       
                           
                       let attrsSize:CGSize = aa.size(withAttributes: [NSAttributedString.Key.font: UIFont.PingFang(size: 14)])
                       
                           let aaL = UILabel()
                       
                           aaL.frame = CGRect(x: 0, y: 0, width: attrsSize.width+2, height: attrsSize.height+2)
                           aaL.text = aa
                           aaL.font = UIFont.PingFang(size: 14)
                       if reply.isMe {
                           aaL.textColor = UIColor(red: 86/255.0, green: 172/255.0, blue: 245/255.0, alpha: 1)
                           aaL.backgroundColor = UIColor(red: 86/255.0, green: 172/255.0, blue: 245/255.0, alpha: 1)
                       }else{
                           aaL.backgroundColor = UIColor.clear
                       }
                        
                           aaL.clipsToBounds = true
                           aaL.layer.cornerRadius = 4
                           aaL.textAlignment = .center

                           //调用方法，转化成Image
                       
                      let image = TalkfunSharedTools.imageWithUIView(aaL)
                   
                       
                       //创建Image的富文本格式
                       let attach = NSTextAttachment()
                       attach.bounds = CGRect(x: 0, y: -(aaL.bounds.size.height/4), width: aaL.bounds.size.width, height: aaL.bounds.size.height)
                  //这个-2.5是为了调整下标签跟文字的位置
                       attach.image = image;
                       //添加到富文本对象里
               
                      let  imageStr = NSAttributedString.init(attachment: attach)
                   
                   //加入文字前面
                       contentAttrStr.insert(imageStr, at: 0)
                       
                       
                   }
                      
                        //14  是左右边距
                   
                        let contentDict = TalkfunSharedTools.getSizeLabel(labelString: contentAttrStr, labelWidth:self.frame.size.width-55-15, labelfont: UIFont.PingFang(size: 14))
                   
                   
                        return contentDict.height+36.5
                        
               }

           }

           
           else  if(model.isBroadcast)
           {
            //公共广播
     
               
              let String = TalkfunSharedTools.getAttributedText(model.msg, fontSize: UIFont.PingFang(size: 14), foregroundColor: UIColor.white)
              
              //14  是左右边距
              
               let contentDict =  TalkfunSharedTools.getSizeLabel(labelString: String, labelWidth:self.frame.size.width-26.5-26.5, labelfont: UIFont.PingFang(size: 14))
               
               
              
              //13  是上下的间距   20 是用户名字高度  3  是与名字的距离     10  是上间距
         
              return contentDict.height+13+13+20+3+12.5
               
              
           
           }else
           {
               
               
               return 0
           }
          
       }
    
    
    //添加聊天数据
    @objc func setChat(_ model:TF1to16LiveChatData)
    {
      self.chatArray.add(model)
      self.tableView.reloadData()

     self.tableView.estimatedRowHeight = 0
     self.tableView.estimatedSectionFooterHeight = 0
     self.tableView.estimatedSectionHeaderHeight = 0
        
    let indexpath = NSIndexPath.init(row: self.chatArray.count - 1, section: 0)
        
    self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
             
    }
    @objc func chatDel(_ uuid:String)
    {
        
        for i in 0..<self.chatArray.count
        {
        let model = self.chatArray[i] as! TF1to16LiveChatData

            if (model.uuid == uuid) {
                self.chatArray.remove(model)

                break
            }
        }
        self.tableView.reloadData()
       
    }
    @objc func setAnnouncement(_ model:TFAnnouncement)
    {
        self.forHeaderDict = model
        self.tableView.reloadData()
     
    }
    @objc func setFlowersDict(_ model:TFLiveFlowerData)
    {
        var flower:String =  ""

        if (model.amount==1) {
            flower =  "[flower]"
        }else  if (model.amount==2) {
            flower =  "[flower][flower]"
        }else if (model.amount==3) {
            flower =  "[flower][flower][flower]"
        }

        let chatData = TF1to16LiveChatData()
        chatData.msg = flower
        chatData.time = model.sendtime as String
        chatData.nickname = model.nickname as String
        chatData.uid = model.uid as String
        chatData.isChat = true
        chatData.isMe = model.isMe
        self.setChat(chatData)
    
       
    }
    //公共广播
    @objc func setPublicBroadcasting(_ model:TF1to16LiveChatData)
    {
        self.setChat(model)
     
    }

    //奖励
    @objc func setAwardModel(_ model:TF1to16LiveChatData)
    {
        self.chatArray.add(model)
        self.tableView.reloadData()
        self.tableView.estimatedRowHeight = 0
        self.tableView.estimatedSectionFooterHeight = 0
        self.tableView.estimatedSectionHeaderHeight = 0

        let indexpath = NSIndexPath.init(row: self.chatArray.count - 1, section: 0)
            
        self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)

    }
    @objc func chatIsDisable(_ isChat:Bool)
    {
        self.inputFieldView.isHidden = isChat
        self.isDisable = isChat
        self.layoutSubviews()
        self.tableView.reloadData()
       
    }
    //禁言所有人
    @objc func chatDisableAll(_ isChat:Bool)
    {
        self.inputFieldView.isHidden = isChat
        self.disableAll = isChat
        self.layoutSubviews()
        self.tableView.reloadData()
    }

    //更新语言切换
    @objc func upDataLanguage()
    {
        
        let votingContentLabelString = NSMutableAttributedString.getAttributed(string: "无聊天内容", font: UIFont.PingFang(size: 18), foregroundColor: UIColor(red: 173/255.0, green: 204/255.0, blue: 222/255.0, alpha: 1))
      
        self.chcdtLabel.attributedText = votingContentLabelString
    }
}
